package org.web.base.helper.filter;

import org.apache.commons.lang3.StringUtils;
//import org.apache.http.client.utils.URIUtils;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;

public class URIHelper {
    public static String QUESTION_MARK = "?";
    public static String AND_MARK = "&";
    public static String EQUAL_MARK = "=";


    public static String addParamToURL(String url, String key, String value) throws URISyntaxException {
        URI uri = new URI(url);
        if (StringUtils.isNotBlank(uri.getQuery())) {
            url = url + AND_MARK + key + EQUAL_MARK + value;
        } else {
            url = url + QUESTION_MARK + key + EQUAL_MARK + value;
        }
        return url;
    }

    public static String removeParamToURL(String url, String key, String value) {
        String parma = key + EQUAL_MARK + value;
        url = StringUtils.remove(url, parma);
        url = StringUtils.removeEnd(url,AND_MARK);
        return url;
    }

    /**
     * 去除url指定参数
     * @param url
     * @param name
     * @return
     */
    public static String removeParamForKeys(String url, String ...name){
        for (String s : name) {
            // 使用replaceAll正则替换,replace不支持正则
            url = url.replaceAll("&?"+s+"=[^&]*","");
        }
        return url;
    }

    public static void main(String[] args) {
        System.out.println(removeParamForKeys("http://www.web.com?a=1","a"));

    }
}
